<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\admin\BaseAdminController;
use think\facade\View;
use app\admin\model\Message as MessageModel;

class Message extends BaseAdminController
{
    /**
     * 消息列表
     */
    public function index()
    {
        View::assign('title', '我的消息');
        return View::fetch();
    }

    /**
     * 查看消息
     */
    public function view()
    {
        $id = input('id/d');
        $obj = MessageModel::where('id', $id)->where('admin_id', UID)->find();
        View::assign('title', '查看消息');
        if (empty($obj)) {
            return View::fetch('dashboard/message404');
        }
        View::assign('item', $obj);
        if ($obj->is_read == 0) {
            $obj->is_read = 1;
            $obj->save();
        }
        return View::fetch();
    }

    /**
     * 批量操作消息
     */
    public function post()
    {
        $type = input('type', 3);
        $arr = input('arr/a', []);
        if ($type == 0) {
            // 全部已读
            MessageModel::update(['is_read' => 1], ['admin_id' => UID]);
        }
        if ($arr) {
            // 标记为已读
            if ($type == 1) {
                MessageModel::where('admin_id', UID)->where('id', 'in', $arr)->save(['is_read' => 1]);
            }
            // 删除消息
            if ($type == 2) {
                MessageModel::destroy(function($query) use ($arr){
                    $query->where('admin_id', UID)->where('id', 'in', $arr);
                });
            }
        }
        return json(['msg' => '']);
    }

    /**
     * 获取消息列表
     */
    public function data()
    {
        $offset = input('offset/d');
        $limit = input('limit/d');
        $obj = new MessageModel;
        $obj = $obj->where('admin_id', UID);
        $total = $obj->count();
        $list = $obj->field('id,title,create_time,is_read')->order(['id' => 'desc'])->limit($offset, $limit)->select();
        return json([
            'total' => $total,
            'rows' => $list,
        ]);
    }
}
